package com.qf.system.user.controller;




import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;














import com.qf.system.role.model.Role;
import com.qf.system.role.service.RoleService;
import com.qf.system.user.model.SystemUser;
import com.qf.system.user.service.SystemUserServiceI;
import com.qf.util.AppUtil;
import com.qf.util.Jurisdiction;
import com.qf.util.PageData;
import com.qf.util.common.Const;
import com.qf.util.controller.BaseController;




/**
*
* 项目名称：qf
* 类名称：SystemUserController
* 类描述：用户管理
* 创建人：周广文
* 创建时间：2015年5月13日 下午2:02:00
* 修改人：周广文
* 修改时间：2015年5月13日 下午2:02:00
* 修改备注：
* @version
*
*/
@Controller
@RequestMapping("/qjqwmain/systemuser")
public class SystemUserController  extends BaseController{
    @Resource(name="systemuserService")
    private SystemUserServiceI systemuserService;  // 系统用户管理service
    @Resource(name="roleService") 
    private RoleService roleService;   // 权限service
    
    
	protected Logger logger = Logger.getLogger(this.getClass()); //log4j	
	String menuUrl = "/qjqwmain/systemuser/listUsers"; //菜单地址(权限用)
	/**
	 * 判断用户名是否存在
	 */
	@RequestMapping(value="/hasU")
	@ResponseBody
	public Object hasU(){
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			if(systemuserService.findByUId(pd) != null){
				errInfo = "error";
			}
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		map.put("result", errInfo);				//返回结果
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 判断邮箱是否存在
	 */
	@RequestMapping(value="/hasE")
	@ResponseBody
	public Object hasE(){
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			
			if(systemuserService.findByUE(pd) != null){
				errInfo = "error";
			}
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		map.put("result", errInfo);				//返回结果
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 判断编码是否存在
	 */
	@RequestMapping(value="/hasN")
	@ResponseBody
	public Object hasN(){
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			if(systemuserService.findByUN(pd) != null){
				errInfo = "error";
			}
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		map.put("result", errInfo);				//返回结果
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	* addUser(跳转到添加用户页面)
	* TODO(响应get请求)
	* TODO(获取权限列表)
	* TODO(跳转到添加用户页面)
	* @param 
	* @param @return
	* @return ModelAndView  对象
	* @Exception 异常对象
	* @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	@RequestMapping("/toAddUser")
    public ModelAndView addUser() throws Exception{
		ModelAndView mv=new ModelAndView();
		List<com.qf.system.role.model.Role> roleList;
		
		roleList = roleService.listAllERRoles();			//列出所有二级角色
		
		mv.addObject("msg", "saveU");
		mv.addObject("roleList", roleList);
    	mv.setViewName("/WEB-INF/system/user/add_user");
    	return mv;
		
    }
	/**
	 * 去新增用户页面
	 */
	@RequestMapping(value="/goAddU")
	public ModelAndView goAddU()throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		List<com.qf.system.role.model.Role> roleList;
		
		roleList = roleService.listAllERRoles();			//列出所有二级角色
		
		mv.setViewName("/WEB-INF/system/user/user_edit");
		mv.addObject("msg", "saveU");
		mv.addObject("pd", pd);
		mv.addObject("roleList", roleList);

		return mv;
	}
	/**
	* saveU(新增用户)
	* TODO(接收前台传入的用户对象)
	* TODO(验证用户对象,如有错误返回Errors)
	* TODO(设置用户最新登录时间为当前时间)
	* TODO(加密用户密码,后台用户密码使用shiro的加密方式)
	* TODO(添加完成返回到用户管理)
	* @param SystemUser
	* @param @return 设定文件
	* @return ModelAndView
	* @Exception 异常对象
	* @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	@RequestMapping("/saveU")
	public ModelAndView saveU(@Validated @ModelAttribute("systemUser") SystemUser systemUser ,Errors errors) throws Exception{
		ModelAndView mv=new ModelAndView();
		SystemUser u=systemUser;
		u.setLast_login(new Date().toString());
		String passwd = new SimpleHash("SHA-1", u.getName(), u.getPassword()).toString();	//密码加密
//		String passwd =new AES().encrypt(u.getPASSWORD().toString());
		
		u.setPassword(passwd);
		u.setUser_id(this.get32UUID());
		PageData pd=new PageData();
		pd=this.getPageData();
		 if(errors.hasErrors()) {  
			 mv.setViewName("/WEB-INF/system/error/error_all");
			 logger.error("新增用户失败,原因未通过后端验证"+errors.getObjectName());
	            return mv;  
	        }  else{
	        	
	    			
	    			
	    			if(null == systemuserService.findByUId(pd)){
	    				if(Jurisdiction.buttonJurisdiction(menuUrl, "add")){int i= systemuserService.saveUser(u);} //判断新增权限
	    				mv.addObject("msg","success");
	    			}else{
	    				mv.addObject("msg","failed");
	    			}
	    			mv.setViewName("save_result");
	    			
	        }

		return mv;
	}
	
	
	
	/**
	 * 去修改用户页面
	 */
	@RequestMapping(value="/goEditU")
	public ModelAndView goEditU() throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		
		//顶部修改个人资料
		String fx = pd.getString("fx");
		
		//System.out.println(fx);
		
		if("head".equals(fx)){
			mv.addObject("fx", "head");
		}else{
			mv.addObject("fx", "user");
		}
		
		List<Role> roleList = roleService.listAllERRoles();			//列出所有二级角色
		pd = systemuserService.findByUId(pd);							//根据ID读取
		mv.setViewName("/WEB-INF/system/user/user_edit");
		mv.addObject("msg", "editU");
		mv.addObject("pd", pd);
		mv.addObject("roleList", roleList);
		
		return mv;
	}
	/**
	 * 修改用户
	 */
	@RequestMapping(value="/editU")
	public ModelAndView editU() throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		if(pd.getString("PASSWORD") != null && !"".equals(pd.getString("PASSWORD"))){
			pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString());
		}
		if(Jurisdiction.buttonJurisdiction(menuUrl, "edit")){systemuserService.editU(pd);}
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	* list(获取用户列表)
	* TODO(查询用户列表)
	* @param name
	* @param @return 设定文件
	* @return ModelAndView
	* @Exception 异常对象
	* @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	@RequestMapping("listUsers")
	public ModelAndView list(com.qf.util.entity.Page page){
		ModelAndView mv=new ModelAndView();
		try {
			PageData  pd=new PageData();
			pd=this.getPageData();
			String USERNAME = pd.getString("user_name");
			
			if(null != USERNAME && !"".equals(USERNAME)){
				USERNAME = USERNAME.trim();
				pd.put("user_name", USERNAME);
			}
			
			String lastLoginStart = pd.getString("lastLoginStart");
			String lastLoginEnd = pd.getString("lastLoginEnd");
			
			if(lastLoginStart != null && !"".equals(lastLoginStart)){
				lastLoginStart = lastLoginStart+" 00:00:00";
				pd.put("lastLoginStart", lastLoginStart);
			}
			if(lastLoginEnd != null && !"".equals(lastLoginEnd)){
				lastLoginEnd = lastLoginEnd+" 00:00:00";
				pd.put("lastLoginEnd", lastLoginEnd);
			} 
			
			page.setPd(pd);
			List<PageData>	userList = systemuserService.listPdPageUser(page);			//列出用户列表
			List<Role> roleList = roleService.listAllERRoles();						//列出所有二级角色
			
			mv.addObject("userList", userList);
			mv.addObject("roleList", roleList);
			mv.addObject("pd", pd);
			mv.addObject(Const.SESSION_QX,this.getHC());	//按钮权限
			
			mv.setViewName("/WEB-INF/system/user/user_list");
		} catch (Exception e) {
			// TODO: handle exception
		}

		return mv;
		
	}
	
	
	
	
	
	
	
	/**
	 * 显示用户列表(tab方式)
	 */
	@RequestMapping(value="/listtabUsers")
	public ModelAndView listtabUsers(com.qf.util.entity.Page page)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		List<PageData>	userList = systemuserService.listAllUser(pd);			//列出用户列表
		mv.setViewName("/WEB-INF/system/user/user_tb_list");
		mv.addObject("userList", userList);
		mv.addObject("pd", pd);
		mv.addObject(Const.SESSION_QX,this.getHC());	//按钮权限
		return mv;
	}
	
	
	
	
	
	/**
	 * 获取头部信息
	 */
	
	/**
	* getList(获取用户信息)
	* TODO(获取shiro管理的session对象userpds)
	* TODO(判断session中是否用用户对象)
	* TODO(如果没有则通过session中的用户名读取用户对象)
	* @param name
	* @param @return 设定文件
	* @return String DOM对象
	* @Exception 异常对象
	* @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	@RequestMapping(value="/head/getUname")
	@ResponseBody
	public Object getList() {
		PageData pd = new PageData();
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			pd = this.getPageData();
			List<PageData> pdList = new ArrayList<PageData>();
			
			//shiro管理的session
			Subject currentUser = SecurityUtils.getSubject();  
			Session session = currentUser.getSession();
			
			PageData pds = new PageData();
			pds = (PageData)session.getAttribute("userpds");
			
			if(null == pds){
				String USERNAME = session.getAttribute(Const.SESSION_USERNAME).toString();	//获取当前登录者loginname
				pd.put("user_name", USERNAME);
				pds = systemuserService.findByUId(pd);
				session.setAttribute("userpds", pds);
			}
			
			pdList.add(pds);
			map.put("list", pds);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
		return AppUtil.returnObject(pd, map);
	}
	/**
	 * 删除用户
	 */
	@RequestMapping(value="/deleteU")
	public void deleteU(PrintWriter out){
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			if(Jurisdiction.buttonJurisdiction(menuUrl, "del")){
				systemuserService.deleteU(pd);
				}
			out.write("success");
			out.close();
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
	}
	
	/**
	 * 批量删除
	 */
	@RequestMapping(value="/deleteAllU")
	@ResponseBody
	public Object deleteAllU() {
		PageData pd = new PageData();
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			pd = this.getPageData();
			List<PageData> pdList = new ArrayList<PageData>();
			String USER_IDS = pd.getString("USER_IDS");
			
			if(null != USER_IDS && !"".equals(USER_IDS)){
				String ArrayUSER_IDS[] = USER_IDS.split(",");
				if(Jurisdiction.buttonJurisdiction(menuUrl, "del")){
					systemuserService.deleteAllU(ArrayUSER_IDS);
					}
				pd.put("msg", "ok");
			}else{
				pd.put("msg", "no");
			}
			
			pdList.add(pd);
			map.put("list", pdList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
		return AppUtil.returnObject(pd, map);
	}
	
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));
	}
	

	/* ===============================权限================================== */
	public Map<String, String> getHC(){
		Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
		Session session = currentUser.getSession();
		return (Map<String, String>)session.getAttribute(Const.SESSION_QX);
	}
	/* ===============================权限================================== */
}
